package com.itheima.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.File;


/**
 * @author Zhang_Han
 * @version 1.0
 * @date 2020/9/26 19:13
 */
public class QNYUpLoadUtil {
    public static final String accessKey = "tAjxdgCEEQZuD4v5pToXUeCer-oKGH4Aq1hnHimz";
    public static final String secretKey = "emQDBKrEfB1KI9v9KSZWi0_8eBA2Jif4pZa0718m";
    public static final String bucket = "itheima-health-0001";

    public static void upload(byte[] uploadBytes, String fileName) {
        Configuration cfg = new Configuration(Region.region0());
        UploadManager uploadManager = new UploadManager(cfg);
        String key = fileName;
        try {
            //byte[] uploadBytes = "C:/Users/Windows/Pictures/images/df.png".getBytes("utf-8");
            //如何把文件转换成byte数组？
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(uploadBytes, key, upToken);
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
    }
}
